package cn.smbms.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField;

import cn.smbms.biz.ProviderBiz;
import cn.smbms.biz.RoleBiz;
import cn.smbms.biz.UserBiz;
import cn.smbms.entity.Provider;
import cn.smbms.entity.Role;
import cn.smbms.entity.User;
import utils.Counts;

@Controller
@RequestMapping("/user")
public class UserControll extends BaseControll {
	
	@Autowired
	private UserBiz userBiz;
	
	@Autowired
	private RoleBiz roleBiz;

	@Autowired
	private ProviderBiz providerBiz;
	 
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String doLogin(@RequestParam("userCode") String userCode,@RequestParam("userPassword") String userPassword,HttpSession session,HttpServletRequest req) {
		try {
			User user = userBiz.getLoginUser(userCode, userPassword);

			if(user==null) {
				req.setAttribute("msg", "您输入的用户不正确!");
				return "login";
				
			}else {
				List<Provider> providerlist = providerBiz.getProvider();
				List<Role> rolelist = roleBiz.getRoleList();
				session.setAttribute("roleList", rolelist);
				session.setAttribute("user", user);
				session.setAttribute("providerList", providerlist);
				return "frame";	
			}
		} catch (Exception e) {
			
			return "login";
		}
		
	} 
	
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String toLogin() {
		return "login";
	}
	
	@RequestMapping(value="/getUserList")
	public String getUserList(@RequestParam(value="queryname",required=false) String userName,
			@RequestParam(value="queryUserRole",required=false) Integer userRole, 
			@RequestParam(value="pageIndex",required=false) Integer currentPageNo,
			Model model) {
		int pageSize = 5;
		
		int count = userBiz.getUserCount(userName, userRole);  
		
		int totalPageCount = 0;
		if(count>0) {
			totalPageCount = (count-1)/pageSize+1;  
			
		}
		if(null==currentPageNo) {
			currentPageNo = 1;
		}
		List<User> list = userBiz.getUserList(userName, userRole, currentPageNo, pageSize);
		
		model.addAttribute("userList", list);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("currentPageNo", currentPageNo);
		model.addAttribute("totalCount", count);
		model.addAttribute("userName", userName);
		model.addAttribute("queryUserRole", userRole);
		return "userlist";
	}
	
	@RequestMapping(value="/addUser",method=RequestMethod.GET)
	public String toAddUser() {
		return "useradd";
	}
	
	@RequestMapping(value="/addUser",method=RequestMethod.POST)
	public String addUser(@Valid @ModelAttribute("user") User user,BindingResult bindingResult,
			@RequestParam(value="idPicPaths",required=false) MultipartFile mf,HttpSession session,HttpServletRequest request) {
		boolean flag = false;
		boolean blag = false;
		String path=null;
		if(bindingResult.hasErrors()) {
			return "useradd";
		}
		User u = (User)session.getAttribute(Counts.USER_SESSION);
		user.setCreatedBy(u.getId());
		user.setCreationDate(new Date());
		
		if(mf.isEmpty()) {
			return "useradd";
		}else {
			String originalFilename = mf.getOriginalFilename();
			String ext=FilenameUtils.getExtension(originalFilename);
			String prefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
			
			try {
				
				String fileName = prefix+"_"+(System.currentTimeMillis()+RandomUtils.nextInt(1000000))+"."+ext;
				
				String realPath =request.getServletContext().getRealPath("/static/uploadFile");
				path="/static/uploadFile/fileName";
				File file = new File(realPath,fileName);
				mf.transferTo(file);
				flag= true;
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
				return "forward:useradd";
			}
		}
		user.setIdPicPath(path);
		int count = userBiz.add(user);
		if(count>0) {
			blag= true;
		}
		
		if(flag&&blag) {
			return "redirect:/user/getUserList";
		}else {
			return "forward:useradd";
		}
	
	}
	
	/*@RequestMapping("/view")
	public String showUser(@RequestParam("uid") Integer id,Model model) {
		User user = userBiz.getUserById(id);
		model.addAttribute("user", user);
		return "userview";
	}*/
	
	/*@RequestMapping(value="/view",method=RequestMethod.GET,produces= {"application/json;charset=UTF-8"})*/
	@RequestMapping(value="/view",method=RequestMethod.GET)
	@ResponseBody
	public Object view(@RequestParam("uid") Integer id) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			User user = userBiz.getUserById(id);
			if(user==null) {
				map.put("result", "nodata");
			}else {
				map.put("result", "data");
				map.put("user", user);
			}
		} catch (Exception e) {
			// TODO: handle exception
			map.put("result", "exception");
		}
		return  JSONArray.toJSONString(map);
	}
	
	
	@RequestMapping(value="/modify",method=RequestMethod.GET)
	public String toModify(@RequestParam("uid") Integer id,Model model) {
		User user = userBiz.getUserById(id);
		model.addAttribute("user", user);
		return "usermodify";
	}
	
	@RequestMapping(value="/modify",method=RequestMethod.POST)
	public String doModify(User user,HttpSession session,Model model) {
		User u = (User)session.getAttribute(Counts.USER_SESSION);
		user.setCreatedBy(u.getId());
		user.setCreationDate(new Date());
		int n = userBiz.modify(user);
		if(n>0) {
			return "redirect:/user/getUserList";
		}else {
			model.addAttribute("user", user);
			return "usermodify";
		}
		
	}
	
	/*@RequestMapping(value="/delete")
	public String deleteUser(@RequestParam("uid") Integer id,HttpServletRequest request) {
		int n = userBiz.deleteUserById(id);
		System.out.println(n);
		if(n>0) {
			request.setAttribute("msg", "删除成功");
		}else {
			request.setAttribute("msg", "删除失败");
		}
		return "redirect:/user/getUserList";
	}*/
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object deleteUser(@RequestParam("id") Integer id) {
		Map<String,Object> map = new HashMap<>();
		try {
			int n = userBiz.deleteUserById(id);
			if(n>0) {
				map.put("delresult", "true");
			}else {
				map.put("delresult", "false");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			map.put("delresult", "exception");
		}
		return JSONArray.toJSONString(map);
	}
	
	
	@RequestMapping(value="/getUserCode")
	@ResponseBody
	public Object getUserCode(@RequestParam("userCode") String userCode) {
		Map<String,Object> map = new HashMap<>();
		try {
			User user = userBiz.getUserCode(userCode);
			if(user!=null) {
				map.put("isexist", "exist");
			}else {
				map.put("isexist", "noexist");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("isexist", "exception");
		}
		return JSONArray.toJSONString(map);
	}
	
	//密码修改
	@RequestMapping(value="/topwdmodify",method=RequestMethod.GET)
	public Object topwdModify() {
		return "pwdmodify";
	}
	
	@RequestMapping(value="/dopwdmodify",method=RequestMethod.GET)
	@ResponseBody
	public Object pwdModify(@RequestParam(value="oldpassword") String oldPwd,HttpSession session) {
		Map<String,Object> map = new HashMap<>();
		User u = (User)session.getAttribute("user");
		String pwd = u.getUserPassword();
		Integer id = u.getId();
		if(pwd.equals(oldPwd)) {
			map.put("result", "true");
		}else {
			map.put("result","false");
		}
		
		return JSONArray.toJSONString(map);
	}
	
	
	
}
